package com.wenhuitec.productlib.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gzwh.weblib.bean.NzDinnerRegion;
import com.gzwh.weblib.bean.NzProductCategory;
import com.gzwh.weblib.bean.Result;
import com.gzwh.weblib.utils.MyObserver;
import com.gzwh.weblib.utils.RequestUtils;
import com.wenhuitec.productlib.R;
import com.wenhuitec.productlib.entity.ProductFoods;
import com.wenhuitec.productlib.entity.Sku;
import com.wenhuitec.productlib.ui.adapter.CategoryManagerAdapter;
import com.wenhuitec.productlib.ui.view.ShowSkuView;
import com.wenhuitec.sysui.TitleBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FoodsEditActivity extends AppCompatActivity {

    private Context mContext;

    private ImageView iv_food;

    private ShowSkuView showSkuView;

    private List<Sku> skuList = new ArrayList<>();
    private boolean updateOrSave = false;

    public static void startAct(Context context, ProductFoods productFoods) {
        Intent intent = new Intent(context, FoodsEditActivity.class);
        intent.putExtra("data", JSONObject.toJSONString(productFoods));
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_foods_edit);
        this.mContext = this;
        iv_food = findViewById(R.id.iv_food);
        showSkuView = findViewById(R.id.showSkuRv);
        try {
            String data = this.getIntent().getExtras().getString("data");
            ProductFoods productFoodList = JSONObject.parseObject(data, ProductFoods.class);
            updateOrSave = true;

        } catch (Exception e) {
//            e.printStackTrace();
        }
        new TitleBuilder(this).setTitleText(updateOrSave ? "编辑商品" : "新增商品")
//                .setLeftIco(R.drawable.yp)
                .setLeftIcoListening((view) -> finish());

        ActivityResultLauncher<Intent> register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent intent = result.getData();
                    if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                        Bundle myBundle = intent.getExtras();
                        String data = myBundle.getString("data");
                        skuList = JSONArray.parseArray(data, Sku.class);
                        showSkuView.setVisibility(View.VISIBLE);
                        showSkuView.setList(skuList);
                    }
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Bitmap bitmap = getBitmap("https://gzwh2024.oss-cn-guangzhou.aliyuncs.com/cqxm/xm2.png");
                if (bitmap != null) {
                    Message msg = new Message();
                    msg.what = 0;// 说明你是谁
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }

            }
        }).start();

        findViewById(R.id.skuBut).setOnClickListener(view -> {
            register.launch(new Intent(mContext, SkuEditActivity.class));
        });
        findViewById(R.id.attrBut).setOnClickListener(view -> {

            startActivity(new Intent(mContext, AttrEditActivity.class));
        });
        findViewById(R.id.feedBut).setOnClickListener(view -> {
            startActivity(new Intent(mContext, FeedEditActivity.class));
        });

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == 0) {
                Bitmap bitmap = (Bitmap) msg.obj;
                iv_food.setImageBitmap(bitmap);
            }

        }

    };

    // bitmap------>位图
    public Bitmap getBitmap(String uri) {
        HttpURLConnection conn = null;
        try {
            // 1、获得图片的url
            URL url = new URL(uri);

            // 2、获得网络连接
            conn = (HttpURLConnection) url.openConnection();

            // 3、设置请求的一些常用参数
            conn.setReadTimeout(3000);// 设置连接去读取数据的最长时间
            conn.setConnectTimeout(3000);// 设置超时
            conn.setDoInput(true);// 设置请求可以让服务器写入数据

            // 4、真正的请求图片，然后把从服务器上请求的二进制流保存到inputStream里面
            conn.connect();
            InputStream in = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            return bitmap;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 5、关闭网络连接
        finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

}
